// 存储变量名
let storageKey = 'storage_data'
// 存储节点变量名
let storageNodeKeys = [ 'avatar', 'name', 'token', 'nick', 'signature' ]
// 存储的数据
export function storageData () {
	return uni.getStorageSync(storageKey) || {}
}

export const storage = {
  set: function(key, value) {
    if (storageNodeKeys.indexOf(key) != -1) {
      let tmp = uni.getStorageSync(storageKey)
      tmp = tmp ? tmp : {}
      tmp[key] = value
      uni.setStorageSync(storageKey, tmp)
	  console.log(storageKey, '设置成功', storageData())
    } else {
		console.log('请前往storage进行配置')
	}
  },
  get: function(key) {
    return storageData()[key] || ""
  },
  remove: function(key) {
    let tem = storageData();
		delete tem[key];
		uni.setStorageSync(storageKey, tem);
  },
  clean: function() {
    uni.removeStorageSync(storageKey)
  }
}



const exporeType = {
	'setTime': 's',
	'value': 'v',
	'expire': 'e'
}

export const storageExpire = {
	
	// expire 单位 s
	set: function (key, value, expire) {
		if (expire && typeof expire === 'number') {
			let expireObj = new Object()
			expireObj[exporeType.setTime] =  Date.now() / 1000
			expireObj[exporeType.value] = value,
			expireObj[exporeType.expire] =  expire
			storage.set(key, JSON.stringify(expireObj))
		} else {
			console.log('注意 expire 的类型：', typeof expire)
		}

	},
	
	get: function(key) {
      	let storageRes = storage.get(key)
		if (storageRes) {
			let expireObj = JSON.parse(storageRes)
			if(expireObj[exporeType.expire] && (Date.now()/1000 - expireObj[exporeType.setTime] < expireObj[exporeType.expire] )) {
				return expireObj[exporeType.value]
			} else {
				// 时间间隔大于 期限
				storage.remove(key)
				return null
			}
		
		} else {
			return ''
		}
	}
}


